﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO.Ports;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading;
using DS_Gimnasio;

namespace BS_Gimnasio.General
{
    [DataContract()]
    public class cls_EnviarSMS
    {
        #region Variables

        private string _comPort;
        private string _numero;
        protected string _error;
        private string _sms;
        private SerialPort _serialPort;

        #endregion

        #region Propiedades

        [DataMember()]
        public string ComPort
        {
            get { return _comPort; }
            set { _comPort = value; }
        }

        [DataMember()]
        public string Numero
        {
            get { return _numero; }
            set { _numero = value; }
        }

        [DataMember()]
        public string Error
        {
            get { return _error; }
            set { _error = value; }
        }

        [DataMember()]
        public string SMS
        {
            get { return _sms; }
            set { _sms = value; }
        }

        [DataMember()]
        public SerialPort SerialPort
        {
            get { return _serialPort; }
            set { _serialPort = value; }
        }

        #endregion

        #region Metodos

        private void Iniciar()
        {
            SerialPort = new SerialPort()
            {
                PortName = _comPort,
                BaudRate = 115200,
                Parity = Parity.None,
                DataBits = 8,
                StopBits = StopBits.One,
                Handshake = Handshake.RequestToSend,
                DtrEnable = true,
                RtsEnable = true,
                NewLine = System.Environment.NewLine,
            };

        }

        public cls_EnviarSMS EnviarSMS()
        {
            Iniciar();
            SerialPort.Open();

            try
            {
                SerialPort.WriteLine("AT" + (char)(13));
                Thread.Sleep(10);

                SerialPort.WriteLine("AT+CMGF=1" + (char)(13));
                Thread.Sleep(10);

                Numero = "\"" + Numero + "\"";

                SerialPort.WriteLine("AT+CMGS=" + _numero);
                Thread.Sleep(10);

                SerialPort.WriteLine(">" + _sms + (char)(26));
                SerialPort.Close();
            }

            catch (Exception ex)
            {
                Error = ex.Source;

                SerialPort.Close();
            }

            return this;
        }

        #endregion

    }
}
